<template>
  <div class="class-detail-page">
    <el-card shadow="never" style="margin-bottom: 20px">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><School /></el-icon>
            班级详情
          </span>
          <div>
            <el-button @click="handleEdit">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button @click="handleBack">
              <el-icon><Back /></el-icon>
              返回
            </el-button>
          </div>
        </div>
      </template>

      <el-skeleton :loading="loading" :rows="5" animated>
        <div class="class-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="班级名称">
              <span class="highlight">{{ classInfo.className }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="年级">
              {{ classInfo.grade }}
            </el-descriptions-item>
            <el-descriptions-item label="班主任">
              {{ classInfo.headTeacher || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="学生人数">
              <el-tag type="primary">{{ classInfo.studentCount }} 人</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="班级平均分">
              <el-tag
                v-if="classInfo.studentCount > 0"
                :type="getScoreType(classInfo.averageScore)"
              >
                {{ classInfo.averageScore }}
              </el-tag>
              <span v-else>-</span>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDate(classInfo.createdAt) }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">
              {{ classInfo.description || '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-skeleton>
    </el-card>

    <!-- 课程统计 -->
    <el-card shadow="never" style="margin-bottom: 20px" v-if="courseStats.length > 0">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><DataAnalysis /></el-icon>
            课程统计
          </span>
        </div>
      </template>

      <el-table :data="courseStats" stripe>
        <el-table-column prop="courseName" label="课程名称" width="150" />
        <el-table-column prop="count" label="参考人数" width="120" align="center">
          <template #default="{ row }">
            <el-tag>{{ row.count }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="average" label="平均分" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getScoreType(row.average)">{{ row.average }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="max" label="最高分" width="120" align="center">
          <template #default="{ row }">
            <el-tag type="success">{{ row.max }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="min" label="最低分" width="120" align="center">
          <template #default="{ row }">
            <el-tag type="danger">{{ row.min }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 学生列表 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><User /></el-icon>
            学生列表
          </span>
          <span class="card-extra">共 {{ students.length }} 名学生</span>
        </div>
      </template>

      <el-table :data="students" stripe>
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column label="课程成绩" min-width="300">
          <template #default="{ row }">
            <div v-if="row.scores && row.scores.length > 0" class="scores-container">
              <el-tag
                v-for="(score, index) in row.scores"
                :key="index"
                :type="getScoreType(score.score)"
                style="margin: 2px"
              >
                {{ score.courseName }}: {{ score.score }}
              </el-tag>
            </div>
            <span v-else class="no-scores">暂无成绩</span>
          </template>
        </el-table-column>
        <el-table-column label="平均分" width="100" align="center">
          <template #default="{ row }">
            <el-tag
              v-if="row.scores && row.scores.length > 0"
              :type="getScoreType(calculateAverage(row.scores))"
            >
              {{ calculateAverage(row.scores) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="viewStudent(row._id)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="students.length === 0" description="该班级还没有学生" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getClass, getClassStatistics } from '@/api/class'

const router = useRouter()
const route = useRoute()

// 数据
const loading = ref(false)
const classInfo = reactive({
  className: '',
  grade: '',
  headTeacher: '',
  description: '',
  studentCount: 0,
  averageScore: 0,
  createdAt: ''
})
const students = ref([])
const courseStats = ref([])

// 加载班级详情
const loadClassDetail = async () => {
  try {
    loading.value = true
    const res = await getClass(route.params.id)
    Object.assign(classInfo, res.data.data)
    students.value = res.data.data.students || []
  } catch (error) {
    ElMessage.error('加载班级信息失败')
    router.back()
  } finally {
    loading.value = false
  }
}

// 加载课程统计
const loadCourseStats = async () => {
  try {
    const res = await getClassStatistics(route.params.id)
    courseStats.value = res.data.data.courseStats || []
  } catch (error) {
    console.error('加载课程统计失败:', error)
  }
}

// 编辑
const handleEdit = () => {
  router.push(`/classes/edit/${route.params.id}`)
}

// 返回
const handleBack = () => {
  router.back()
}

// 查看学生详情
const viewStudent = (studentId) => {
  router.push(`/students/edit/${studentId}`)
}

// 计算平均分
const calculateAverage = (scores) => {
  if (!scores || scores.length === 0) return 0
  const total = scores.reduce((sum, item) => sum + item.score, 0)
  return (total / scores.length).toFixed(2)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 获取分数标签类型
const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return ''
  if (score >= 70) return 'warning'
  return 'danger'
}

onMounted(() => {
  loadClassDetail()
  loadCourseStats()
})
</script>

<style scoped>
.class-detail-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.card-extra {
  font-size: 14px;
  color: #909399;
}

.class-info {
  margin: 20px 0;
}

.highlight {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
}

.scores-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.no-scores {
  color: #909399;
  font-size: 14px;
}
</style>
